package edu.scau.pos.service;

import edu.scau.core.Enum.OrderStatus;
import edu.scau.core.exection.BusinessProcessException;
import edu.scau.core.util.ServletUtils;
import edu.scau.pos.domain.Orders;
import edu.scau.pos.domain.SaleLineItem;
import edu.scau.pos.mapper.OrdersMapper;
import edu.scau.pos.vo.OrdersVo;
import edu.scau.pos.vo.SaleItemVo;
import edu.scau.system.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class OrdersServiceImpl implements OrdersService{
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private SaleLineItemService saleLineItemService;
    @Override
    public List<OrdersVo> listAll() {
        return ordersMapper.listAll();
    }

    @Override
    public OrdersVo findOrdersByOrderId(String orderId) {
        return ordersMapper.findOrdersVoByOrderId(orderId);
    }

    @Override
    public Orders findByOrderId(String orderId) {
        return ordersMapper.findOrdersByOrderId(orderId);
    }

    @Override
    public int updateOrders(Orders orders) {
        String updateBy=tokenService.getLoginUser(ServletUtils.getRequest()).getUsername();
        Date updateDate=new Date();
        if(!this.isExisted(orders.getOrderId())){
            throw  new IllegalArgumentException("订单不存在！");
        }
        orders.setUpdateBy(updateBy);
        orders.setUpdateTime(updateDate);
        return ordersMapper.updateOrders(orders);
    }

    @Override
    public int updateOrdersByOrdersVo(OrdersVo ordersVo) {
      return 0;
    }

    private List<SaleLineItem> fomateSaleLineItemVo(List<SaleItemVo> saleLineItems) {
        List<SaleLineItem> saleLineItemsList=new ArrayList<>();
        for (SaleItemVo saleLineItem : saleLineItems) {
            SaleLineItem saleLineItemVo=new SaleLineItem(saleLineItem);
            saleLineItemsList.add(saleLineItemVo);
        }
        return saleLineItemsList;
    }

    @Override
    public int deleteOrdersById(String orderId) {
        return ordersMapper.deleteOrdersById(orderId);
    }

    /**
     * 前提是SaleLineItems关联orderid
     * @param orders 对象
     * @return
     */
    @Override
    @Transactional
    public int insertOrders(Orders orders) {
        String createBy=tokenService.getLoginUser(ServletUtils.getRequest()).getUsername();
        Date createDate=new Date();
        int isDeleted=0;
        if(orders.getOrderId().isEmpty()){
            throw  new IllegalArgumentException("订单编号不能为空！");
        }
        if(this.isExisted(orders.getOrderId())){
            throw  new IllegalArgumentException("订单编号重复！");
        }
        orders.setCreateBy(createBy);
        orders.setCreateTime(createDate);
        orders.setIsDeleted(isDeleted);
        if(orders.getSaleLineItems()!= null && !orders.getSaleLineItems().isEmpty()){
            int res1 = saleLineItemService.insertBatch(orders.getSaleLineItems());
            if(res1<=0){
                throw new IllegalArgumentException("商品细目入库失败");
            }
        }
        int res= ordersMapper.insertOrders(orders);
        return res;
    }

    @Override
    @Transactional
    public int insertOrdersByOrrdersVo(OrdersVo ordersVo) {
        String createBy=tokenService.getLoginUser(ServletUtils.getRequest()).getUsername();
        Date createDate=new Date();
        int isDeleted=0;
        Orders order=new Orders(ordersVo);
        if(ordersVo.getSaleLineItems()!= null && !ordersVo.getSaleLineItems().isEmpty()){
            List<SaleLineItem> saleLineItems=this.fomateSaleLineItemVo(ordersVo.getSaleLineItems()).stream().map(saleLineItem -> {
                saleLineItem.setCreateBy(createBy);
                saleLineItem.setCreateTime(createDate);
                saleLineItem.setOrderId(ordersVo.getOrderId());
                return saleLineItem;
            }).toList();
            int res= saleLineItemService.insertBatch(saleLineItems);
            if(res<=saleLineItems.size()){
                log.info("插入saleLIneItem失败");
                throw  new BusinessProcessException("插入失败");
            }
            order.setSaleLineItems(saleLineItems);
        }
        return  ordersMapper.insertOrders(order);
    }

    @Override
    public List<OrdersVo> listByOrders(OrdersVo ordersVo) {
        return ordersMapper.listByOrders(ordersVo);
    }

    /**
     * 查找所有缺货补发订单
     * @return
     */
    @Override
    public List<OrdersVo> listAllBlock() {
        OrdersVo orders=new OrdersVo();
        orders.setStatus(OrderStatus.Backorder.getSignal());
        return ordersMapper.listByOrders(orders);
    }

    @Override
    public List<OrdersVo> findOrdersOfSale(String orderId) {
        Orders orders=ordersMapper.findOrdersByOrderId(orderId);
        return ordersMapper.findOrderVoOfSale(orders.getSaleId());
    }

    @Override
    public List<OrdersVo> listByOrdersOfStatus(int status) {
        OrdersVo orders=new OrdersVo();
        orders.setStatus(status);
        List<OrdersVo> ordersList = this.listByOrders(orders);
        return ordersList;
    }


    @Override
    public boolean isExisted(String orderId) {
        return ordersMapper.isExisted(orderId)>0;
    }

    /**
     *根据挂单订单查找同一个saleId的订单
     * @param orderId
     * @return
     */
    @Override
    public Orders findRelatedOrder(String orderId) {
        Orders orders=ordersMapper.findOrdersByOrderId(orderId);
        if(orders==null){
            throw new BusinessProcessException("订单不存在");
        }
        String saleId=orders.getSaleId();
        List<Orders> ordersList=ordersMapper.findOrderOfSale(saleId);
        Orders res=new Orders();
        for (Orders order : ordersList) {
            if(! order.getOrderId().equals(orderId)){
                res=order;
            }
        }
        return res;
    }




}
